package com.sergiandreplace.kaboom.format.zip;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.sergiandreplace.kaboom.format.FormatBitmapExtractorThread;
import com.sergiandreplace.kaboom.format.FormatManager.MessageHandler;
import com.sergiandreplace.kaboom.util.GraphicsUtil;
import com.sergiandreplace.kaboom.util.MyLog;

public class ZipBitmapExtractorThread extends FormatBitmapExtractorThread
{

	

	private ZipManager zManager;

	public ZipBitmapExtractorThread(ZipManager zManager, String filename, int size, MessageHandler messageHandler)
	{
		super(filename, size, messageHandler);
		this.zManager = zManager;
	}

	@Override
	public void run()
	{
		super.run();

		byte[] bytes = null;
		boolean failed = false;
		File file = new File(zManager.getUri());
		FileInputStream fin;
		Bitmap result = null;
		try
		{
			fin = new FileInputStream(file);

			ZipInputStream zis = new ZipInputStream(fin);
			boolean found = false;

			ZipEntry zEntry;
			zEntry = zis.getNextEntry();
			while (zEntry != null && !found)
				if (zEntry.getName().equals(getFilename()))
					found = true;
				else
				{
					zis.closeEntry();
					zEntry = zis.getNextEntry();
				}
			if (found)
			{
				MyLog.l("Page " + getFilename() + " found");
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int count;
				while ((count = zis.read(buffer)) != -1)
				{

					baos.write(buffer, 0, count);
				}
				bytes = baos.toByteArray();
			}
		}
		catch (IOException e)
		{
			failed = true;
		}
		if (!failed)
		{
			
			BitmapFactory.Options op = new BitmapFactory.Options();
			// op.inPreferredConfig = Bitmap.Config.ARGB_4444;

			if (this.getSize() > 0)
			{
				boolean loaded = false;
				Bitmap bigResult = null;
				while (!loaded)
				{
					try
					{
						bigResult = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, op);
						loaded = true;
					}
					catch (java.lang.OutOfMemoryError ex)
					{
						
					}
				}
				result = GraphicsUtil.getResizedBitmap(bigResult, getSize());
				bigResult.recycle();
			}
			else
			{
				result = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, op);
			}
		}
		
		finish (result,1);
	}

}
